<template>
  <div>
    <div class="block">
      <span class="demonstration">商品分类:</span>
      <el-input v-model="name" placeholder="请输入内容" style="width:250px"></el-input>
      <el-button type="primary" round @click="getSpecList()" icon="el-icon-search"></el-button><br>
      <el-button type="primary" @click="addSpec()">添加规格</el-button>
      <el-button type="danger" @click="deleteMany()">批量删除</el-button>
    </div>
    {{ids}}
    <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange"
      @current-change="currentChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="id" label="ID" width="180">
      </el-table-column>
      <el-table-column prop="specName" label="规格名称" width="180">
      </el-table-column>
      <el-table-column prop="keyList" label="规格属性">
        <template slot-scope="scope">
          <div v-for="item in scope.row.keyList" v-bind="item">
            <span>{{item.keyName}}</span><br>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="keyList" label="商品属性">
        <template slot-scope="scope">
          <div v-for="item in scope.row.keyList" v-bind="item">
            <span v-for="key in item.valueList" v-bind="key">
              {{key.valueName}}
            </span>
            <br>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="updateSpecs(scope.row.id)" type="text" size="small">编辑</el-button>
          <el-button type="text" v-if="scope.row.children==null" size="small" @click="deleteById(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Form -->
    <el-dialog title="规格属性" :visible.sync="firstDialogFormVisible">
      <el-form :model="specs">
        <el-form-item label="规格名称">
          <el-input v-model="specs.specName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model="specsKey.keyName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="规格值">
          <el-input v-model="specsValue.valueName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="firstDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="firstBeSure()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="规格属性" :visible.sync="dialogFormVisible">
      {{specs}}
      <el-form :model="specs">
        <el-form-item label="规格名称">
          <el-input v-model="specs.specName" autocomplete="off"></el-input>
        </el-form-item>
        <span :key="index" v-for="(key,index) in specs.keyList">
          <el-tag closable @close='handleClose(key)'>
            {{key.keyName}}
          </el-tag><br>
          <el-tag :key="index" v-for="(value,index) in key.valueList" closable :disable-transitions="false"
            @close="handleClose2(key,value)">
            {{value.valueName}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="specsValue.valueName" ref="saveTagInput"
            size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm(key.valueList)"
            style="width:65px">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加</el-button>
          <br>
        </span>
        <el-button type="primary" @click="addNewSpec()">添加新规格</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAdd()">取 消</el-button>
        <el-button type="primary" @click="saveSpec()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data () {
    //这里存放数据
    return {
      token: "",
      ids: [],
      multipleSelection: [],
      inputVisible: false,
      inputValue: "",
      formLabelWidth: 250,
      tableData: [],
      name: "",
      firstDialogFormVisible: false,
      dialogFormVisible: false,
      specs: {
        specName: "",
        keyList: []
      },
      specsKey: {
        keyName: "",
        valueList: []
      },
      specsValue: {
        valueName: ""
      }
    };
  },
  //计算属性 类似于 data 概念
  computed: {
    headers () {
      return {
        "token": (localStorage.token || ""),
        "type": "1"
      }
    }
  },
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    deleteMany () {//批量删除
      this.multipleSelection.map((item) => {
        this.ids.push(item.id);
      });
      this.deleteSpesc();
    },
    currentChange (currentRow) {
      console.log(currentRow);
    },
    handleSelectionChange (val) {
      // console.log(val, "val")
      this.multipleSelection = val;
    },
    toggleSelection (rows) {
      console.log(rows);
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    deleteSpesc () {//删除
      this.$confirm('此操作将永久删除该规格, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .delete("http://localhost:8001/coco/goods/specs/deleteSpecs?ids=" + this.ids, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: '删除规格成功!',
                type: 'success'
              });
              this.getSpecList();
            } else {
              this.$message.error('删除规格失败!');
            }
            this.ids = [];
          }).catch((err) => { });
      })
    },
    deleteById (id) {
      this.ids.push(id);
      this.deleteSpesc();
    },
    updateSpecs (id) {//编辑框
      this.$http
        .get("http://localhost:8001/coco/goods/specs/findSpecsById/" + id, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.specs = data.data;
        }).catch((err) => { });
      this.firstDialogFormVisible = true;
      this.dialogFormVisible = true;
    },
    saveSpec () {//保存规格
      if (this.specs.id != null) {
        this.$http
          .put("http://localhost:8001/coco/goods/specs/updateSpecs/" + this.specs.id, this.specs, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: '修改规格成功!',
                type: 'success'
              });
              this.getSpecList();
              this.dialogFormVisible = false;
              this.firstDialogFormVisible = false;
            } else {
              this.$message.error('修改规格失败!');
            }
          }).catch((err) => { });
      } else {
        this.$http
          .post("http://localhost:8001/coco/goods/specs/addSpecs", this.specs, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: '添加规格成功!',
                type: 'success'
              });
              this.getSpecList();
              this.dialogFormVisible = false;
              this.firstDialogFormVisible = false;
            } else {
              this.$message.error('添加规格失败!');
            }
          }).catch((err) => { });
      }
    },
    addNewSpec () {//添加新规格
      this.dialogFormVisible = false;
    },
    closeAdd () {//取消
      this.specs.keyList = [];
      this.specsKey = {
        keyName: "",
        valueList: []
      };
      this.specsValue = {
        valueName: ""
      }
      this.dialogFormVisible = false;
    },
    handleClose2 (key, value) {
      let a = this.specs.keyList.indexOf(key);
      this.specs.keyList[a].valueList.splice(this.specs.keyList[a].valueList.indexOf(value), 1);
    },
    handleClose (key) {
      this.specs.keyList.splice(this.specs.keyList.indexOf(key), 1);
      key.ValueList = [];
    },

    showInput () {
      this.inputVisible = true;
      // this.$nextTick(_ => {
      //   this.$refs.saveTagInput.$refs.input.focus();
      // });
    },

    handleInputConfirm (valueList) {
      if (this.specsValue.valueName != null && this.specsValue.valueName.length > 0) {
        valueList.push(this.specsValue);
      }
      this.inputVisible = false;
      this.specsValue = {
        valueName: "",
      }
    },
    addSpec () {//添加规格
      this.specs = {
        specName: "",
        keyList: []
      };
      this.specsKey = {
        keyName: "",
        valueList: []
      };
      this.specsValue = {
        valueName: ""
      };

      this.firstDialogFormVisible = true;
    },
    firstBeSure () {//第一次确认
      this.specsKey.valueList.push(this.specsValue);
      this.specs.keyList.push(this.specsKey);
      this.dialogFormVisible = true;
      this.specsKey = {
        keyName: "",
        valueList: []
      };
      this.specsValue = {
        valueName: ""
      }
    },
    getSpecList () {//获取规格的集合
      this.$http
        .get('http://localhost:8001/coco/goods/specs/findSpecList?name=' + this.name, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code != 0) {
            this.$message({
              message: data.message,
              type: 'error'
            })
            this.$router.push("/");
          }
          this.tableData = data.data;
          this.tableData.forEach(item => {
            console.log(item);
          })
          console.log(this.tableData);
        }).catch((err) => { });
    }
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created () {
    this.token = localStorage.getItem("token");
    this.getSpecList();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () {

  },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有 keep-alive 缓存功能，这个函数会触发
}
</script>
<style scoped>
</style>